package container.impl;

import container.MyContext;
import container.MyWrapper;
import life.LifecycleBase;
import server.MyClassLoader;
import server.MyHttpServlet;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MyMappedContext extends LifecycleBase implements MyContext {

    private String contextName;

    private MyClassLoader classLoader;

    private Map<String,MyWrapper> myWrapperMap = new ConcurrentHashMap<>();;

    @Override
    protected void initInternal() {
        for (String s : myWrapperMap.keySet()) {
            MyWrapper myWrapper = myWrapperMap.get(s);
            try {
                Class<?> clazz = classLoader.findClass(myWrapper.getClassName());
                MyHttpServlet myHttpServlet = (MyHttpServlet) clazz.getClassLoader().loadClass(myWrapper.getClassName()).newInstance();
                myHttpServlet.init();
                myWrapper.setServlet(myHttpServlet);
                System.out.println(myHttpServlet.getClass().getName()+" init");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void startInternal() {
        System.out.println(this.getClass().getName()+" startContext");
    }

    @Override
    public void setContextName(String contextName) {
        this.contextName =  contextName;

    }

    @Override
    public String getContextName() {
        return contextName;
    }

    @Override
    public void setClassLoad(MyClassLoader classLoader) {
        this.classLoader = classLoader;
    }

    @Override
    public void setMyWrapper(MyWrapper myWrapper) {
        myWrapperMap.put(myWrapper.getUrlPattern(),myWrapper);
    }

    @Override
    public Map<String, MyWrapper> getMyWrapperMap() {
        return myWrapperMap;
    }

}
